package com.shoppingmall.mainfragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.example.zyh.toolslib.base.BaseFragment;
import com.example.zyh.toolslib.widget.TitleBar;
import com.shoppingmall.R;
import com.shoppingmall.adapter.ShopCartListAdapter;
import com.shoppingmall.bean.GoodsBean;
import com.shoppingmall.bean.ShopCartBean;
import com.shoppingmall.bean.ShopCartGroupBean;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class ShopCartFragment extends BaseFragment implements ShopCartListAdapter.CheckInterface, ShopCartListAdapter.ModifyCountInterface {

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.fg_shopcart_tv_pay)
    TextView accountTv;
    @BindView(R.id.lv_shopcart)
    ExpandableListView shopCartLv;
    @BindView(R.id.fg_shopcart_tv_total_price)
    TextView totalPriceTv;

    /**
     * 记录上次点击按钮的时间
     **/
    private long lastClickTime = 0;
    /**
     * 按钮连续点击最低间隔时间 单位：毫秒
     **/
    public final static int CLICK_TIME = 1200;
    private Boolean isEditState = false;//编辑和完成状态
    private int start = 1;//页码
    private int totalMoney = 0;//总钱数
    private int totalCount = 0;//总个数
    List<GoodsBean> selectedList;//选中的列表
    //    private List<ShopCartBean> mList = new ArrayList<>();
    private ShopCartListAdapter mAdapter;
    private List<ShopCartGroupBean> groups;//组元素数据列表
    private Map<String, List<ShopCartBean>> children;//子元素数据列表
    private String[] series = {"GREKRITI", "Utomorrow", "Pslady"};// 1-格丽缇 2-Utomorrow 3-Pslady


    @Override
    protected int initLayout() {
        return R.layout.fragment_shopcart;
    }

    @Override
    protected void initView(View rootView) {
    }

    @Override
    protected void initData() {

        LogUtils.d("ShopCartFragment:initData+懒加载数据");
        totalPriceTv.setText("¥" + 0);
        isEditState = false;
        titleBar.setRightText("管理");
//        if (!TextUtils.isEmpty(SPUtils.getInstance(mActivity).getSP(Constants.TOKEN))) {
//            getShopCartData();
//        } else {
//            shopCartLv.setVisibility(View.INVISIBLE);
//            ToastUtils.toast("请先登录");
//            startActivityForResult(new Intent(mActivity, LoginActivity.class), Constants.INTENT_LOGIN_CODE);
//        }
        initEvent();
    }

//    @Override
//    protected void initImmersionBar() {
//        super.initImmersionBar();
//        mImmersionBar.fitsSystemWindows(true).statusBarColor(R.color.white).statusBarDarkFont(true, 0.2f).init();
//    }

    private void initEvent() {
        groups = new ArrayList<>();
        children = new HashMap<>();
        selectedList = new ArrayList<>();
        mAdapter = new ShopCartListAdapter(mActivity, groups, children);
        shopCartLv.setAdapter(mAdapter);
        mAdapter.setCheckInterface(this);
        mAdapter.setModifyCountInterface(this);
        titleBar.setRightLayoutVisibility(View.VISIBLE);
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEditState) {
                    isEditState = false;
                    titleBar.setRightText("管理");
                    accountTv.setText("去结算");
                } else {
                    accountTv.setText("删除");
                    titleBar.setRightText("取消");
                    isEditState = true;
                }
            }
        });
        //结算
        accountTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (SharedPreferencesUtil.getInstance(mActivity).getSP(Constants.TOKEN).equals("")) {
//                    return;
//                }
//                if (selectedList.size() == 0) {
//                    return;
//                }
//                postOrder();
            }
        });
        //删除
//        deleteTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (SharedPreferencesUtil.getInstance(mActivity).getSP(Constants.TOKEN).equals("")) {
//                    return;
//                }
//                if (selectedList.size() == 0) {
//                    return;
//                }
//                deleteCart();
//            }
//        });
//        if (!TextUtils.isEmpty(SharedPreferencesUtil.getInstance(mActivity).getSP(Constants.TOKEN))) {
//            getShopCartData();
//        } else {
//            ToastUtils.showShort(mActivity, "请先登录");
//            startActivityForResult(new Intent(mActivity, LoginActivity.class), Constants.INTENT_LOGIN_CODE);
//        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == Constants.INTENT_LOGIN_CANCEL) {
//            ((MainActivity) getActivity()).switchHome();
//        }
//        if (resultCode == Constants.INTENT_LOGIN_OK) {
//            getShopCartData();
//        }
    }

    private void resetCheckBox() {
        for (int i = 0; i < groups.size(); i++) {
            checkGroup(i, false);
        }
    }

    /**
     * 选中组
     */
    @Override
    public void checkGroup(int groupPosition, boolean isChecked) {
        ShopCartGroupBean group = groups.get(groupPosition);
        List<ShopCartBean> childs = children.get(group.getSeriesName());
        for (int i = 0; i < childs.size(); i++) {
            childs.get(i).setChoosed(isChecked);
        }
        mAdapter.notifyDataSetChanged();
        calculate();
    }

    /**
     * 选中子
     */
    @Override
    public void checkChild(int groupPosition, int childPosition, boolean isChecked) {
        boolean allChildSameState = true;//判断该组下面的所有子元素是否是同一种状态
        ShopCartGroupBean group = groups.get(groupPosition);
        List<ShopCartBean> childs = children.get(group.getSeriesName());
        for (int i = 0; i < childs.size(); i++) {
            if (childs.get(i).isChoosed() != isChecked) {
                allChildSameState = false;
                break;
            }
        }
        if (allChildSameState) {
            group.setChoosed(isChecked);//如果所有子元素状态相同，那么对应的组元素被设为这种统一状态
        } else {
            group.setChoosed(false);//否则，组元素一律设置为未选中状态
        }
        mAdapter.notifyDataSetChanged();
        calculate();

    }

    private TextView countView;//记录更改的数字控件，成功后更改

    /**
     * 增加
     */
    @Override
    public void doIncrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        if (fastDoubleClick()) {
            return;
        }
//        if (isChecked) {
        ShopCartBean product = (ShopCartBean) mAdapter.getChild(groupPosition, childPosition);
        int currentCount = product.getNum();
        currentCount++;
        product.setNum(currentCount);
//        ((TextView) showCountView).setText(currentCount + "");
//        }
//        mAdapter.notifyDataSetChanged();
//        calculate();
        updateNum(product.getId(), currentCount);
    }

    /**
     * 减少
     */
    @Override
    public void doDecrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        if (fastDoubleClick()) {
            return;
        }
        ShopCartBean product = (ShopCartBean) mAdapter.getChild(groupPosition, childPosition);
        int currentCount = product.getNum();
//        if (isChecked) {
        currentCount--;
        if (currentCount < 0) {
            currentCount = 0;
        }
        product.setNum(currentCount);
//        ((TextView) showCountView).setText(currentCount + "");
//        }
//        updateNum(product.getId(),currentCount);
//        mAdapter.notifyDataSetChanged();
//        calculate();
        updateNum(product.getId(), currentCount);
    }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给底部的textView进行数据填充
     */
    private void calculate() {
        selectedList.clear();
        totalCount = 0;
        totalMoney = 0;
        for (int i = 0; i < groups.size(); i++) {
            ShopCartGroupBean group = groups.get(i);
            List<ShopCartBean> childs = children.get(group.getSeriesName());
            for (int j = 0; j < childs.size(); j++) {
                ShopCartBean cartBean = childs.get(j);
                if (cartBean.isChoosed()) {
                    GoodsBean goodsBean = new GoodsBean();
                    totalCount++;
                    totalMoney += cartBean.getaPrice() * cartBean.getNum();
                    goodsBean.setaPrice(cartBean.getaPrice());
                    goodsBean.setName(cartBean.getCommName());
                    goodsBean.setImg(cartBean.getImg());
                    goodsBean.setBuyCount(cartBean.getNum());
                    goodsBean.setId(cartBean.getCommId());
                    goodsBean.setScale(cartBean.getScale());
                    goodsBean.setSerise(cartBean.getSerise());
                    goodsBean.setCartId(cartBean.getId());
                    selectedList.add(goodsBean);
                }
            }
        }
        totalPriceTv.setText("¥" + totalMoney);
        accountTv.setText("去支付(" + totalCount + ")");
    }

    /**
     * 查看购物车
     * url:/cart/findPage.action
     * param:token,start,pageSize
     */
    private void getShopCartData() {
//        groups.clear();
//        children.clear();
//        selectedList.clear();
//        if (TextUtils.isEmpty(SharedPreferencesUtil.getInstance(mActivity).getSP(Constants.TOKEN))) {
//            mAdapter.notifyDataSetChanged();
//            return;
//        }
//        FastJsonRequest request = new FastJsonRequest(Constants.SHOPCARTLIST, RequestMethod.POST);
//        request.add("start", start);
//        request.add("pageSize", 30);
//        request.add("token", SharedPreferencesUtil.getInstance(mActivity).getSP(Constants.TOKEN));
//        CallServer.getInstance().request(mActivity, 1, request, httpListener, false, true);
    }

    /**
     * 修改数量
     * url:/cart/updateOne.action
     * param:id,num,token
     */
    private void updateNum(String cartId, int num) {
//        FastJsonRequest request = new FastJsonRequest(Constants.UPDATECARTGOODSNUM, RequestMethod.POST);
//        request.add("id", cartId);
//        request.add("num", num);
//        request.add("token", SharedPreferencesUtil.getInstance(mActivity).getSP(Constants.TOKEN));
//        CallServer.getInstance().request(mActivity, 2, request, httpListener, true, true);
    }

    /**
     * 删除购物车
     * url:/cart/removeOne.action
     * ###### param:cartId,token
     */
    private void deleteCart() {
        String cartId = "";
        for (int i = 0; i < selectedList.size(); i++) {
            cartId = cartId + selectedList.get(i).getId() + ",";
        }
        cartId = cartId.substring(0, cartId.lastIndexOf(","));
//        FastJsonRequest request = new FastJsonRequest(Constants.DELETECART, RequestMethod.POST);
//        request.add("cartId", cartId);
//        request.add("token", SharedPreferencesUtil.getInstance(mActivity).getSP(Constants.TOKEN));
//        CallServer.getInstance().request(mActivity, 3, request, httpListener, true, true);
    }

    /**
     * 提交订单(提交数据格式为Json，且只允许相同系列商品同时提交))
     */
    private void postOrder() {
        int series = selectedList.get(0).getSerise();//获取第一个产品的系列，如果后续有不同系列提示一次只能购买一个系列
        for (int i = 0; i < selectedList.size(); i++) {
            if (selectedList.get(i).getSerise() != series) {
//                showDialog();
                return;
            }
        }
//        Intent intent = new Intent(mActivity, ConfirmOrdersActivity.class);
//        Bundle bundle = new Bundle();
//        bundle.putSerializable("goodslist", (Serializable) selectedList);
//        bundle.putString("pageType", "shopcart");
//        intent.putExtras(bundle);
//        startActivity(intent);
    }

//    HttpListener<JSONObject> httpListener = new HttpListener<JSONObject>() {
//
//        @Override
//        public void onSucceed(int what, Response<JSONObject> response) {
//            BaseBean baseBean = response.get().toJavaObject(BaseBean.class);
//            if (baseBean.isStatus()) {
//                if (what == 1) {
//                    shopCartLv.setVisibility(View.VISIBLE);
//                    groups.clear();
//                    children.clear();
//                    selectedList.clear();
//                    ShopCartListBean listBean = JSONObject.parseObject(baseBean.getObj(), ShopCartListBean.class);
//                    groups.addAll(spiltList(listBean.getItem()));
//                    mAdapter.notifyDataSetChanged();
//                }
//                if (what == 2) {
//                    //修改数量
//                    mAdapter.notifyDataSetChanged();
//                    calculate();
//                }
//                if (what == 3) {
//                    //删除
//                    getShopCartData();
//                }
//                //数据更改后，要展开
//                for (int i = 0; i < mAdapter.getGroupCount(); i++) {
//                    shopCartLv.expandGroup(i);//关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
//                }
//
//            } else {
//                if (what != 1) {
//                    ToastUtils.showShort(mActivity, baseBean.getMsg());
//                }
//
//            }
//        }
//
//        @Override
//        public void onFailed(int what, Response<JSONObject> response) {
//
//        }
//    };

    /**
     * 对结果按系列进行分类汇总
     * 1-格丽缇 2-Utomorrow 3-Pslady
     */
    private List<ShopCartGroupBean> spiltList(List<ShopCartBean> list) {
        List<ShopCartGroupBean> groupList = new ArrayList<>();
        List<ShopCartBean> krtProducts = new ArrayList<>();
        List<ShopCartBean> utProducts = new ArrayList<>();
        List<ShopCartBean> psProducts = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ShopCartBean cartBean = list.get(i);
            if (cartBean.getSerise() == 1) krtProducts.add(cartBean);
            if (cartBean.getSerise() == 2) utProducts.add(cartBean);
            if (cartBean.getSerise() == 3) psProducts.add(cartBean);
        }
        if (krtProducts.size() != 0) {
            ShopCartGroupBean groupBean = new ShopCartGroupBean();
            groupBean.setSeriesName(series[0]);
            groupList.add(groupBean);
            children.put(series[0], krtProducts);
        }
        if (utProducts.size() != 0) {
            ShopCartGroupBean groupBean = new ShopCartGroupBean();
            groupBean.setSeriesName(series[1]);
            groupList.add(groupBean);
            children.put(series[1], utProducts);
        }
        if (psProducts.size() != 0) {
            ShopCartGroupBean groupBean = new ShopCartGroupBean();
            groupBean.setSeriesName(series[2]);
            groupList.add(groupBean);
            children.put(series[2], psProducts);
        }

        return groupList;
    }

    /**
     * 防止多次点击
     */
    private boolean fastDoubleClick() {
        if (System.currentTimeMillis() - lastClickTime <= CLICK_TIME) {
            return true;
        }
        lastClickTime = System.currentTimeMillis();
        return false;
    }

//    private void showDialog() {
//        final WarmTipDialog dialog = new WarmTipDialog(mActivity);
//        dialog.setMessage("一次只能提交同一个系列的商品");
//        dialog.setOnConfirmClickListener("知道了", new WarmTipDialog.OnConfirmClickListener() {
//            @Override
//            public void confirmClick() {
//                dialog.dismiss();
//            }
//        });
//        dialog.show();
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String msg) {
        if (TextUtils.equals("refreshShopcart", msg)) {
            totalPriceTv.setText("¥" + 0);
            accountTv.setText("去支付");
            isEditState = false;
            titleBar.setRightText("编辑");
            //处理逻辑
            getShopCartData();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
